import { Component, OnInit } from '@angular/core';
import HeadImage from 'src/app/model/HeadImage';
import { MessageService } from '../../../core/services/message-service/message.service'
import { NetService } from '../../../core/services/net-service/net.service'
import { UtilsService } from '../../../core/services/utils-service/utils.service'
import { WebApi, base_uri, admin_uri, article_uri } from '../../../core/config/webapi_mapping';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam } from 'ng-zorro-antd/upload';
import News from 'src/app/model/News';
import { NewsQuery } from '../../../model/Query'
import E from 'wangeditor'
import { DssModel } from '../../../model/DssModel'
import * as moment from 'moment';

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {

  // 轮播图

  imageList: Array<HeadImage> = []

  image: HeadImage = new HeadImage()

  isVisible = false;

  isOkLoading = false;

  modelTitle: string = '新增轮播图'

  uploadPicAction: string = ''

  isEdit: boolean = false

  // 新闻

  newsList: Array<News> = []

  news: News = new News()

  searchValue: string = ''

  pageRequest: NewsQuery = new NewsQuery()

  isNewsVisible = false

  modelNewsTitle: string = '新增新闻资讯'

  isNewsOkLoading = false

  isNewsEdit: boolean = false

  editor: any = null

  articleUri: string = ''

  isPreViewShow: boolean = false

  iframeUri: string = ''

  // 签名
  //sign: string = 'KCnmheZFCM/7dE/vTMfQLTiMl2QBcLrJo=' // KSKCnmheZFCM/7dE/vTMfQLTiMl2QBcLrJo=

  sign: string = 'KSKCnmheZFCM/7dE/vTMfQLTiMl2QBcT28NpORgLrJo='

  constructor(private messageService: MessageService, private netService: NetService, private msg: NzMessageService, private utils: UtilsService) { }

  ngOnInit(): void {
    this.uploadPicAction = WebApi.utils.uploadPic
    this.articleUri = admin_uri + article_uri
    this.queryHeadImage()
    this.initNews()
    // this.sign = this.messageService.getState('code') === undefined ? this.sign : this.messageService.getState('code')
  }

  // 轮播图
  async queryHeadImage() {
    const result = await this.netService.getAsync(WebApi.headImage.queryAll, null)
    if (result.state === '0') {
      this.imageList = result.data
    }
  }

  showEditModel(flag: string, _image?: HeadImage) {
    if (flag === '1') {
      this.image = new HeadImage()
      this.image.image = base_uri + "/static/images/empty.jpg"
      this.modelTitle = '新增轮播图'
      this.isEdit = false
    } else {
      this.image = JSON.parse(JSON.stringify(_image))
      this.modelTitle = '修改轮播图'
      this.isEdit = true
    }
    this.isVisible = true
  }

  async handleOk(): Promise<void> {

    this.isOkLoading = true
    let result: any = {}

    if (!this.isEdit) {
      result = await this.netService.postAsync(WebApi.headImage.addHeadImage, this.image);
    } else {
      result = await this.netService.putAsync(WebApi.headImage.updateHeadImage, this.image);
    }
    if (result.state === '0') {
      this.msg.success('提交成功')
    } else {
      this.msg.error('提交失败')
    }
    await this.queryHeadImage()
    this.isVisible = false
    this.isOkLoading = false

  }

  handleCancel(): void {
    this.isVisible = false;
  }

  handleChange(info: NzUploadChangeParam): void {
    if (info.file.status !== 'uploading') {
      // console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      this.msg.success(`${info.file.name} 文件成功上传`)
      this.image.image = info.file.response.location
    } else if (info.file.status === 'error') {
      this.msg.error(`${info.file.name} 文件成功失败.`)
    }
  }

  async confirmDelete(item: HeadImage) {
    const result = await this.netService.deleteAsync(WebApi.headImage.logicDeleteHeadImage + '/?id=' + item.id, null);
    if (result.state === '0') {
      this.msg.success('提交成功')
    }
    await this.queryHeadImage()
    this.isVisible = false
    this.isOkLoading = false
  }

  async pubHeadImage(item: HeadImage, pub: number) {
    this.image = JSON.parse(JSON.stringify(item))
    this.image.is_pub = pub
    const result = await this.netService.putAsync(WebApi.headImage.updateHeadImage, this.image)
    if (result.state === "0") {
      pub === 1 ? this.msg.success('发布成功') : this.msg.success('取消成功')
      await this.queryHeadImage();
    }
  }

  // 新闻
  initNews() {
    this.queryNews()
  }

  async queryNews(reset?: boolean) {
    if (reset) {
      this.pageRequest.pageNum = 1
      this.pageRequest.pageSize = 5
    }
    this.pageRequest.loading = true
    const result = await this.netService.postAsync(WebApi.news.queryNewsPage, this.pageRequest)
      if (result.state === '0') {
        this.pageRequest.loading = false
        this.pageRequest.pageNum = result.data.pageNum
        this.pageRequest.pageSize = result.data.pageSize
        this.pageRequest.totalSize = result.data.totalSize
        this.newsList = result.data.content
      }
  }

  search() {
    this.queryNews()
  }

  openNewsModel(flag: string, _news?: News) {
    if (flag === '1') {
      this.news = new News()
      this.modelNewsTitle = '新增新闻资讯'
      this.isNewsEdit = false
    } else {
      this.news = JSON.parse(JSON.stringify(_news));
      this.modelNewsTitle = '修改新闻资讯'
      this.isNewsEdit = true
    }
    this.isNewsVisible = true
  }

  afterNewsModel() {
    if (this.editor === null) {
      this.editor = new E("#content_editor")
      this.editor.customConfig.uploadImgServer = WebApi.utils.uploadWangEditorPic
      this.editor.customConfig.uploadImgMaxLength = 1
      this.editor.customConfig.uploadFileName = 'file';
      this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
      this.editor.create()
    }

    this.editor.txt.html(this.news.content)
  }

  resetSearch() {
    this.searchValue = ''
  }

  indexSearchData(type: string) {
    if (type === 'index') {
      this.queryNews()
    } else if (type === 'size') {
      this.pageRequest.pageNum = 1
      this.queryNews()
    } else {
    }
  }

  handleNewsCancel() {
    this.isNewsVisible = false
  }

  async handleNewsOk() {
    this.isNewsOkLoading = true;
    this.news.content = this.editor.txt.html()

    let result : any = {}
    let dssResult: any = {}
    if (!this.isNewsEdit) {
      result = await this.netService.postAsync(WebApi.news.addNews, this.news)
      const model = this.getDssModel(result.data.id.toString(), 0);
      const param = {
        url: WebApi.dss.addCatarcNews,
        method: 'post',
        data: JSON.stringify(model)
      }
      dssResult = await this.netService.postFormAsync(WebApi.utils.proxyHttp, param);

      if (dssResult.code !== 200 || dssResult.data.service.route.serviceResponse.code !== 'S000') {
        this.msg.error('dss同步失败，数据新增失败');
        // 2020-11-24 如果dss同步失败，就删除该条数据
        const deleteResult = await this.netService.deleteAsync(WebApi.news.logicDeleteNews + '?id=' + result.data.id)
        if (deleteResult.state !== '0') {
          this.msg.error('本地同步删除失败');
        }
      } else {
        // 新增DSS需同步ID
        this.news.id = result.data.id;
        this.news.dss_id = Number.parseInt(dssResult.data.data.id)
        let updateResult = await this.netService.putAsync(WebApi.news.updateNews, this.news);
        if (updateResult.state !== '0') {
          this.msg.success('本地同步失败');
        }
        if (result.state === '0') {
          this.msg.success('提交成功');
        }
      }

    } else {
      
      const model = this.getDssModel(this.news.id.toString(), 1);
      const param = {
        url: WebApi.dss.updateCatarcNews,
        method: 'post',
        data: JSON.stringify(model)
      }
      dssResult = await this.netService.postFormAsync(WebApi.utils.proxyHttp, param);
      if (dssResult.code !== 200 || dssResult.data.service.route.serviceResponse.code !== 'S000') {
        this.msg.error('dss同步失败');
      } else {
        result = await this.netService.putAsync(WebApi.news.updateNews, this.news)
        if (result.state === '0') {
          this.msg.success('提交成功');
        }
      }
    }


    await this.queryNews(true);
    this.isNewsVisible = false;
    this.isNewsOkLoading = false;

  }

  getLink() {
    this.msg.success('新闻链接已经复制到剪切板。')
  }

  async deleteNews(news: News) {
    this.news = news

    const model = this.getDssModel(this.news.id.toString(), 2);
    const param = {
      url: WebApi.dss.delCatarcNews,
      method: 'post',
      data: JSON.stringify(model)
    }
    const dssResult = await this.netService.postFormAsync(WebApi.utils.proxyHttp, param);
    if (dssResult.code !== 200 || dssResult.data.service.route.serviceResponse.code !== 'S000') {
      this.msg.error('dss同步失败');
    } else {
      const result = await this.netService.deleteAsync(WebApi.news.logicDeleteNews + '?id=' + this.news.id)
      if (result.state === "0") {
        this.msg.success('删除成功');
      }
    }
    await this.queryNews(true);
  }

  preViewArticle(item: News) {
    this.iframeUri = admin_uri + article_uri + item.id
    this.isPreViewShow = true
  }

  async pubArticle(item: News, pub: number) {
    this.news = JSON.parse(JSON.stringify(item))
    this.news.is_pub = pub
    const result = await this.netService.putAsync(WebApi.news.updateNews, this.news)
    if (result.state === "0") {
      pub === 1 ? this.msg.success('发布成功') : this.msg.success('取消成功')
      await this.queryNews(true);
    }
  }

  preViewOk() {
    this.isPreViewShow = false
  }

  getImageUrls(htmlStr: string) {
    let imgStrs = htmlStr.match(/<img.*?>/g)

    if (imgStrs === null) {
      return '';
    }
    // 获取每个img url
    let urls = imgStrs.map(url=>{
      return url.match(/\ssrc=['"](.*?)['"]/)[1]
    })

    // 拼接成字符串
    let returnStr = ''
    urls.forEach(element => {
      returnStr = returnStr+ element + ';'
    }); 
    returnStr = returnStr.substr(0,returnStr.length-1);
    return returnStr
  }

  // opr : 0 新增 1 更新 2 删除
  getDssModel(id: string, opr: number) {
    // 20201111 添加 同步dss
    const time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    const dssModel = JSON.parse(JSON.stringify(DssModel))
    dssModel.service.data.control.sign = this.sign
    dssModel.service.data.request.createBy = this.news.author
    dssModel.service.data.request.dept = this.news.author
    dssModel.service.data.request.insideId = id
    dssModel.service.data.request.newsTitle = this.news.title
    dssModel.service.data.request.subTitle = this.news.description
    dssModel.service.data.request.newsContent = this.news.content
    dssModel.service.data.request.picture = this.getImageUrls(this.news.content)
    dssModel.service.data.request.newsCreateTime = moment(this.news.pubTime).format('YYYY-MM-DD HH:mm:ss');
    switch (opr) {
      case 0:
        dssModel.service.route.serviceId = '104'
        dssModel.service.data.request.newsUpdateTime = time
        break;
      case 1:
        dssModel.service.route.serviceId = '103'
        dssModel.service.data.request.newsId = this.news.dss_id.toString()
        
        dssModel.service.data.request.newsUpdateTime = time
        break;
      case 2:
        dssModel.service.route.serviceId = '101'
        dssModel.service.data.request.newsId = this.news.dss_id.toString()
        dssModel.service.data.request.newsUpdateTime = time

        // 删除去掉多余属性
        delete dssModel.service.data.request.createBy
        delete dssModel.service.data.request.dept
        delete dssModel.service.data.request.insideId
        delete dssModel.service.data.request.newsTitle
        delete dssModel.service.data.request.subTitle
        delete dssModel.service.data.request.newsContent
        delete dssModel.service.data.request.picture
        delete dssModel.service.data.request.newsCreateTime
        delete dssModel.service.data.request.newsUpdateTime
        break;
      default:
        break;
    }
    return dssModel;
  }

}
